package com.feign.feignClient.coder;

import com.alibaba.fastjson.JSONObject;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

/**
 * 自定义Decoder,使用阿里的FastJson
 */
public class JsonDecoder implements Decoder {



    @Override
    public Object decode(Response response, Type type) throws FeignException, IOException {
        if (response.status() == 200){
            BufferedReader br = new BufferedReader(response.body().asReader() );
            // 存放数据
            String temp  ;
            StringBuilder builder = new StringBuilder();
            while ((temp = br.readLine()) != null) {
                builder.append(temp );
                builder.append("\r\n");
            }
            String  result = builder.toString().trim() ;
            //若是字符串对象，直接返回
            if (type.getTypeName().contains("String")) {
                return result;
            }
            try {
                String typeName = type.getTypeName();
                int indexStrat =  typeName.indexOf("<");
                String className = typeName;
                //若是List类型
                if(typeName.contains("List") ){
                    className = typeName.substring(indexStrat+1, typeName.indexOf(">"));
                    Class typeClass = Class.forName(className);
                    List list = JSONObject.parseArray(result, typeClass.newInstance().getClass());
                    return   list ;
                }
                Class typeClass = Class.forName(className);
                //实例下塑造型返回
                return JSONObject.parseObject(result,typeClass.newInstance().getClass() );
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }

        }
        return null;

    }


}
